import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

import {
  interceptorsRequest,
  interceptorsResponse,
  interceptorsResponseError,
  config,
} from './util';

export interface HttpResponse<T> {
  body: any;
  msg?: string;
  message?: string;
  code: number | string;
  data: T;
  rows: T;
  [key: string]: any;
}

interface CustomConfig {
  hideTip?: boolean;
  interceptorsRequest?: (x: AxiosRequestConfig) => AxiosRequestConfig;
  interceptorsResponse?: (x: AxiosResponse<HttpResponse<any>>) => any;
  interceptorsResponseError?: (x: any, hideTip?: boolean) => any;
}

const instance = axios.create({
  ...config,
});

export default function http<T = any>(
  data: AxiosRequestConfig,
  customConfig?: CustomConfig
): Promise<HttpResponse<T>> {
  const interceptorsRequestFun =
    customConfig?.interceptorsRequest || interceptorsRequest;
  const obj = interceptorsRequestFun(data);

  return instance(obj)
    .then((response) => {
      const fun = customConfig?.interceptorsResponse || interceptorsResponse;
      return fun(response, customConfig?.hideTip);
    })
    .catch((err) => {
      const fun =
        customConfig?.interceptorsResponseError || interceptorsResponseError;
      return fun(err, customConfig?.hideTip);
    });
}
